﻿#include "formatpanel.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QListWidgetItem>
#include <QFontMetrics>
#include <QPainter>
#include <QDebug>
#include <QGroupBox>
#pragma execution_character_set("utf-8")
FormatPanel::FormatPanel(QWidget* parent)
	: QWidget(parent),
	m_styleList(new QListWidget(this)),
	m_currentStyleLabel(new QLabel(tr("当前样式: 无"), this)),
	m_fontLabel(new QLabel(tr("字体: -"), this)),
	m_sizeLabel(new QLabel(tr("字号: -"), this)),
	m_formatLabel(new QLabel(tr("格式: -"), this)),
	m_clearFormatBtn(new QPushButton(tr("清除格式"), this)),
	m_resetDefaultsBtn(new QPushButton(tr("恢复默认"), this))
{
	initUI();
	initDefaultStyles();

	// 初始化当前Ribbon状态
	m_currentRibbonState =
	{
		"正文",
		"Arial",
		12,
		false,
		false,
		false,
		false,
		"#000000",
		"#FFFFFF"
	};
}

void FormatPanel::initUI()
{
	// 主布局
	QVBoxLayout* mainLayout = new QVBoxLayout(this);
	mainLayout->setContentsMargins(10, 10, 10, 10);
	mainLayout->setSpacing(20);
	// 样式列表
	m_styleList->setIconSize(QSize(200, 40));
	mainLayout->addWidget(m_styleList);

	// 当前样式信息
	QGroupBox* infoGroup = new QGroupBox(tr("当前格式"), this);
	QVBoxLayout* infoLayout = new QVBoxLayout(infoGroup);
	infoLayout->addWidget(m_currentStyleLabel);
	infoLayout->addWidget(m_fontLabel);
	infoLayout->addWidget(m_sizeLabel);
	infoLayout->addWidget(m_formatLabel);
	mainLayout->addWidget(infoGroup);

	// 按钮区域
	QHBoxLayout* buttonLayout = new QHBoxLayout();
	buttonLayout->addWidget(m_clearFormatBtn);
	buttonLayout->addWidget(m_resetDefaultsBtn);
	mainLayout->addLayout(buttonLayout);

	// 连接信号槽
	QObject::connect(m_styleList, &QListWidget::itemClicked,
		this, &FormatPanel::onStyleSelected);
	QObject::connect(m_clearFormatBtn, &QPushButton::clicked,
		this, &FormatPanel::onClearFormatClicked);
	QObject::connect(m_resetDefaultsBtn, &QPushButton::clicked,
		this, &FormatPanel::onResetDefaultsClicked);

	// 设置样式
	setStyleSheet(R"(
        QGroupBox {
            border: 1px solid #c0c0c0;
            border-radius: 4px;
            margin-top: 1ex;
            padding: 10px;
        }
        QGroupBox::title {
            subcontrol-origin: margin;
            subcontrol-position: top center;
            padding: 0 5px;
        }
        QListWidget {
            border: 1px solid #c0c0c0;
            border-radius: 4px;
        }
        QPushButton {
            padding: 5px;
            border-radius: 4px;
            background-color: #f0f0f0;
            border: 1px solid #c0c0c0;
        }
        QPushButton:hover {
            background-color: #e0e0e0;
        }
    )");
}

void FormatPanel::initDefaultStyles()
{
	// 添加默认样式
	FormatStyle title1 =
	{
		"标题1",
		"宋体",
		24,
		true,
		false,
		false,
		false,
		"#000000",
		"#FFFFFF"
	};
	addStyle(title1);

	FormatStyle title2 =
	{
		"标题2",
		"Arial",
		18,
		true,
		false,
		false,
		false,
		"#000000",
		"#FFFFFF"
	};
	addStyle(title2);

	FormatStyle title3 =
	{
		"标题3",
		"Arial",
		14,
		true,
		false,
		false,
		false,
		"#000000",
		"#FFFFFF"
	};
	addStyle(title3);

	FormatStyle normal =
	{
		"正文",
		"Arial",
		12,
		false,
		false,
		false,
		false,
		"#000000",
		"#FFFFFF"
	};
	addStyle(normal);

	FormatStyle bold =
	{
		"强调",
		"Arial",
		12,
		true,
		false,
		false,
		false,
		"#000000",
		"#FFFFFF"
	};
	addStyle(bold);

	FormatStyle code =
	{
		"代码",
		"Consolas",
		12,
		false,
		false,
		false,
		false,
		"#000000",
		"#F0F0F0"
	};
	addStyle(code);

	FormatStyle quote =
	{
		"引用",
		"Times New Roman",
		12,
		false,
		true,
		false,
		false,
		"#666666",
		"#FFFFFF"
	};
	addStyle(quote);

	// 设置默认选中
	setCurrentStyle("正文");
}

void FormatPanel::addStyle(const FormatStyle& style)
{
	if (m_styles.contains(style.name))
	{
		qWarning() << "Style" << style.name << "already exists";
		return;
	}

	m_styles.insert(style.name, style);
	updateStylePreview(m_styles[style.name]);

	QListWidgetItem* item = new QListWidgetItem
	(
		createStylePreviewIcon(style),
		style.name
	);
	item->setData(Qt::UserRole, style.name);
	m_styleList->addItem(item);
}

void FormatPanel::updateStyle(const QString& name, const FormatStyle& style)
{
	if (!m_styles.contains(name))
	{
		qWarning() << "Style" << name << "does not exist";
		return;
	}

	m_styles[name] = style;
	updateStylePreview(m_styles[name]);

	// 更新列表项
	for (int i = 0; i < m_styleList->count(); ++i)
	{
		QListWidgetItem* item = m_styleList->item(i);
		if (item->data(Qt::UserRole).toString() == name)
		{
			item->setIcon(createStylePreviewIcon(style));
			break;
		}
	}

	// 如果当前样式被更新，更新预览
	if (currentStyle() == name)
		updateCurrentStylePreview();
}

void FormatPanel::removeStyle(const QString& name)
{
	if (!m_styles.contains(name))
		return;

	// 移除列表项
	for (int i = 0; i < m_styleList->count(); ++i)
	{
		QListWidgetItem* item = m_styleList->item(i);
		if (item->data(Qt::UserRole).toString() == name)
		{
			delete m_styleList->takeItem(i);
			break;
		}
	}

	m_styles.remove(name);

	// 如果移除的是当前样式，重置预览
	if (currentStyle() == name)
		setCurrentStyle("");
}

void FormatPanel::clearStyles()
{
	m_styleList->clear();
	m_styles.clear();
	setCurrentStyle("");
}

void FormatPanel::setCurrentStyle(const QString& name)
{
	if (name.isEmpty() || !m_styles.contains(name))
	{
		m_currentStyleLabel->setText(tr("当前样式: 无"));
		return;
	}

	// 更新列表选中状态
	for (int i = 0; i < m_styleList->count(); ++i)
	{
		QListWidgetItem* item = m_styleList->item(i);
		if (item->data(Qt::UserRole).toString() == name)
		{
			item->setSelected(true);
			m_styleList->setCurrentItem(item);
			break;
		}
	}

	// 更新预览
	updateCurrentStylePreview();
}

QString FormatPanel::currentStyle() const
{
	QListWidgetItem* currentItem = m_styleList->currentItem();
	if (!currentItem) return "";
	return currentItem->data(Qt::UserRole).toString();
}


void FormatPanel::syncRibbonState
(
	const QString& fontFamily,
	int fontSize,
	bool bold,
	bool italic,
	bool underline
)
{
	// 更新当前Ribbon状态
	m_currentRibbonState.fontFamily = fontFamily;
	m_currentRibbonState.fontSize = fontSize;
	m_currentRibbonState.bold = bold;
	m_currentRibbonState.italic = italic;
	m_currentRibbonState.underline = underline;

	// 更新预览
	updateCurrentStylePreview();
}

void FormatPanel::updateStylePreview(FormatStyle& style)
{
	// 更新样式预览图标
	for (int i = 0; i < m_styleList->count(); ++i)
	{
		QListWidgetItem* item = m_styleList->item(i);
		if (item->data(Qt::UserRole).toString() == style.name)
		{
			item->setIcon(createStylePreviewIcon(style));
			break;
		}
	}
}

void FormatPanel::updateCurrentStylePreview()
{
	QListWidgetItem* currentItem = m_styleList->currentItem();
	if (!currentItem)
	{
		m_currentStyleLabel->setText(tr("当前样式: 无"));
		m_fontLabel->setText(tr("字体: -"));
		m_sizeLabel->setText(tr("字号: -"));
		m_formatLabel->setText(tr("格式: -"));
		return;
	}

	QString styleName = currentItem->data(Qt::UserRole).toString();
	if (!m_styles.contains(styleName))
		return;

	const FormatStyle& style = m_styles[styleName];

	// 更新当前样式标签
	m_currentStyleLabel->setText(tr("当前样式: %1").arg(style.name));
	m_fontLabel->setText(tr("字体: %1").arg(style.fontFamily));
	m_sizeLabel->setText(tr("字号: %1").arg(style.fontSize));

	// 更新格式标签
	QStringList formats;
	if (style.bold) formats << tr("加粗");
	if (style.italic) formats << tr("斜体");
	if (style.underline) formats << tr("下划线");

	if (formats.isEmpty())
		m_formatLabel->setText(tr("格式: 常规"));
	else
		m_formatLabel->setText(tr("格式: %1").arg(formats.join("，")));
}

QIcon FormatPanel::createStylePreviewIcon(const FormatStyle& style)
{
	QPixmap pixmap(200, 50);
	pixmap.fill(QColor(style.backgroundColor));

	QPainter painter(&pixmap);
	QFont font(style.fontFamily, style.fontSize);
	font.setBold(style.bold);
	font.setItalic(style.italic);
	font.setUnderline(style.underline);
	painter.setFont(font);
	painter.setPen(QColor(style.color));

	// 关键：用 QFontMetrics 计算文字基线位置
	QFontMetrics metrics(font);
	QString previewText = style.name;
	QString elidedText = metrics.elidedText(previewText, Qt::ElideRight, 180);

	// 计算垂直居中的 Y 坐标：基线 = 画布高度的一半 + metrics.ascent()/2
	int textY = (pixmap.height() + metrics.ascent()) / 2;

	// 绘制文字（用计算后的 Y 坐标）
	painter.drawText(5, textY, elidedText);

	return QIcon(pixmap);
}

void FormatPanel::onStyleSelected(QListWidgetItem* item)
{
	if (!item) return;

	QString styleName = item->data(Qt::UserRole).toString();
	updateCurrentStylePreview();

	// 发射信号替代调用回调
	emit styleSelected(styleName);
}

void FormatPanel::onClearFormatClicked()
{
	// 发射信号替代调用回调
	emit clearFormatClicked();
}

void FormatPanel::onResetDefaultsClicked()
{
	// 发射信号替代调用回调
	emit resetDefaultsClicked();
}


FormatStyle FormatPanel::getStyle(const QString& name) const
{
	if (m_styles.contains(name))
	{
		return m_styles[name];
	}
	return FormatStyle{ "默认", "Arial", 12, false, false, false, false , "#000000","#FFFFFF" };
}
